# app/__init__.py
import logging
import os
from logging.handlers import RotatingFileHandler
from flask import Flask
from flask_cors import CORS
from .config import Config
from .extensions import redis_conn, limiter
from .models import db
from .routes.device import device_bp
from .routes.useraction import user_bp
from .routes.auth import auth_bp
from .routes.general import general_bp
from .routes.admin import admin_bp  # 导入管理员蓝图
from .routes.announcement import announcement_bp, user_announcement_bp  # 导入公告蓝图和用户公告蓝图
from .routes.repository import repository_bp  # 导入资源库蓝图
from .routes.admin_feedback import admin_feedback_bp  # 导入管理员反馈蓝图
from .routes.feedback import feedback_bp  # 导入用户反馈蓝图
from .database import init_app, initialize_mongodb

def create_app():
    # 应用实例化
    print("🟢 应用初始化开始")  # 调试信息
    app = Flask(__name__)
    CORS(app)
     
    app.config.from_object(Config)
    
    # 配置SQLAlchemy
    app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{Config.MYSQL_USER}:{Config.MYSQL_PASSWORD}@{Config.MYSQL_HOST}:{Config.MYSQL_PORT}/{Config.MYSQL_DB}"
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    print("🔵 配置加载完成")
    
    # 日志配置
    configure_logging(app)
    
    # 扩展初始化
    redis_conn.init_app(app)
    limiter.init_app(app)
    
    # 初始化数据库
    db.init_app(app)
    
    # 注册蓝图
    app.register_blueprint(device_bp, url_prefix='/api')
    app.register_blueprint(user_bp, url_prefix='/api')
    app.register_blueprint(auth_bp, url_prefix='/api')
    app.register_blueprint(general_bp, url_prefix='/api')
    app.register_blueprint(admin_bp, url_prefix='/api')  # 注册管理员蓝图
    app.register_blueprint(announcement_bp, url_prefix='/api/admin')  # 修改公告蓝图前缀，与文档一致
    app.register_blueprint(user_announcement_bp, url_prefix='/api')  # 注册用户公告蓝图
    app.register_blueprint(repository_bp, url_prefix='/api')  # 注册资源库蓝图
    app.register_blueprint(admin_feedback_bp, url_prefix='/api/admin/feedback')  # 注册管理员反馈蓝图
    app.register_blueprint(feedback_bp, url_prefix='/api/feedback')  # 注册用户反馈蓝图
    
    return app

def configure_logging(app):
    """生产环境日志配置"""
    if not app.debug:
        log_dir = os.path.join(app.root_path, 'logs')
        log_file = os.path.join(log_dir, 'app.log')
        
        # 自动创建目录
        if not os.path.exists(log_dir):
            os.makedirs(log_dir, mode=0o755, exist_ok=True)
        
        handler = RotatingFileHandler(
            log_file,  # 使用绝对路径
            maxBytes=1024 * 1024 * 100,
            backupCount=10,
            encoding='utf-8'
        )
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        handler.setFormatter(formatter)
        app.logger.addHandler(handler)
        app.logger.setLevel(logging.INFO)